<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat Demo</title>
</head>
<body>
<div id="container">
    <div class="controls">
        <input type="text" id="nickname">
        <input type="text" id="balance">
        <input type="text" id="inputMsg" value="Hello~">
        <input type="button" id="sendMsg" value="Send">
        <input type="button" id="clean" value="Clean">
    </div>
    <ul>
        <li>list:</li>
    </ul>
    <ul id="msg-list">
    </ul>
</div>
<script src="jquery-3.6.1.min.js" type="text/javascript"></script>
<script src="protocol.js" type="text/javascript"></script>
<script src="pomelo-client-json.js" type="text/javascript"></script>

<script>
    $(document).ready(function () {
        const nickname = 'guest' + Date.now();

        $("#nickname").val(nickname);
        $("#balance").val(1000);

        $("#sendMsg").click(function () {
            var inputMsg = $("#inputMsg").val();

            pomelo.notify('room.room.syncMessage', {
                name: $("#nickname").val(),
                content: inputMsg
            });

            console.log(nickname, inputMsg);
        });

        $("#clean").click(function () {
            $("#msg-list").find("li").remove();
        });
        
        pomelo.init({host: "127.0.0.1", port: 34590, path: '/'}, function () {
            console.log("connected!");

            pomelo.on("onNewUser", onNewUser);
            pomelo.on("onMembers", onMembers);
            pomelo.on("onBalance", onBalance);

            // request login
            pomelo.request("room.room.login", {"nickname": nickname}, function (data) {
                console.log(data);
                if (data.code === 0) {
                    pomelo.on('onMessage', onMessage);
                }
            });
        });
    });

    function onNewUser(data) {
        console.log(data);
        pushMsg({name: 'system', content: data.content});
    }

    function onMembers(data) {
        console.log(data);
        pushMsg({name: 'system', content: "members: " + data.members});
    }

    function onBalance(data) {
        console.log(data);
        $("#balance").val(data.currentBalance);
    }

    function onMessage(msg) {
        console.log(msg);
        pushMsg(msg)
    }

    function pushMsg(msg) {
        var text = "<li>[<span style=\"color:red;\">" + msg.name + "</span>]" + msg.content + "</li>";
        $("#msg-list").append(text);
    }

</script>
</body>
</html>
